<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<?php 
	if( !isset($_COOKIE["username"]) ){
		echo "<script>window.location.href='login.php'</script>";
	}else{
		setcookie("username", $_COOKIE["username"],time() + 900);
	}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Doctor</title>
<link href="css/template.css" rel="stylesheet" type="text/css" />
<link href="css/TestDoctor.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/droplinemenu.js" type="text/javascript"></script>
<script type="text/javascript">
//build menu with DIV ID="myslidemenu" on page:
droplinemenu.buildmenu("nav")
</script>

<link href="css/ui-lightness/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui-1.9.2.custom.js"></script>


<script type="text/javascript">


	var isChange = false;

	function changeFunc(){
		isChange = true;
		document.getElementById("MSG").innerHTML = "";
	}


	function operateClinic(){
		var clinicNo = document.getElementById("clinicNoOpClinic").value;
		var clinicName = document.getElementById("clinicName").value;
		var clinicAddress =jQuery("#clinicAddress").val();
		var clinicDetail = jQuery("#detail").val();
		var postData = "clinicNo=" + clinicNo + "&clinicName=" + clinicName + "&clinicAddress=" + clinicAddress + "&detail=" + clinicDetail;
							
		jQuery.ajax({type:'post', async:false, dataType:'json', url:'add_clinic.php', data:postData, success:function(result){
				if( result.data.status == "success" ){
					alert(jQuery("#operateClinicButton").text() + " success!!!");
					if( jQuery("#operateClinicButton").text() == "Add" ){
						var clinicObject = document.getElementById("clinicNoOpClinic" );
						var option = new Option(result.data.clinicName, result.data.clinicNo);
						option.selected = true;
						clinicObject.options.add(option);
						jQuery("#AddClinicDialog").dialog("option", "buttons", [{text:"Update", id:"operateClinicButton", click:new Function("operateClinic()")}, {text:"Cancel", click:function(){jQuery(this).dialog("close");}}]);
						option = new Option(result.data.clinicName, result.data.clinicNo);
						option.selected = false;
						document.getElementById("clinicNo").options.add(option);
					}
					jQuery("#AddClinicDialog").dialog("close");
				}else{
						
					alert(jQuery("#operateClinicButton").text() + " fail!!!" + result.data.msg);
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
			}
		});
	}

	jQuery(document).ready(function(){

		//initial the operate clinic dialog
		jQuery("#AddClinicDialog").dialog({
			autoOpen:false,
			width:650,
			modal:true,
			buttons:[
					{
						text: "Add",
						id:"operateClinicButton",
						click:new Function("operateClinic()")
					},
					{
						text:"Cancel",
						click:function(){
							jQuery(this).dialog("close");
						}
					}
				]		
		});
		

		
		jQuery("#leaveDialog").dialog({
			autoOpen:false,
			modal:true,
			width:400,
			buttons:[
			         {
				         text:"Yes",
				         click:function(){
					         
				        	if( doctorSubmit() == false ){
				        		jQuery(this).dialog("close");
					        	return;
				        	}
				        	alert("save success!!!!");
				        	isChange = false;
				        	previousPage();
				         }
				         
			         },
			         {
				         text:"No",
				         click:function(){
				        	isChange = false;
				        	previousPage();
				         }
			         },
			         {
				         text:"Cancel",
				         click:function(){
					         jQuery(this).dialog("close");
				         }
			         }
					]
			
		});

		if( document.getElementById("deleteButton").getAttribute("disabled") == "disabled" ){
			document.getElementById("deleteButton").disabled = "disabled";
			
		}
	});



	function popAddClinic(){
		var clinicNoSelect = document.getElementById("clinicNo").value;
		var clinicDialogObject = document.getElementById("clinicNoOpClinic");
		for( var i = 0; i < clinicDialogObject.options.length; i++ ){
			if( clinicDialogObject.options[i].value == clinicNoSelect ){
				clinicDialogObject.options[i].selected = true;
				getClinicInfo();
			}
		}
		jQuery("#AddClinicDialog").dialog("open");
	}

	

	function getClinicInfo(){
		var clinicObject = document.getElementById("clinicNoOpClinic");
		var clinicNo = clinicObject.value;
		jQuery.ajax({type:'post', async:false,dataType:'json',  url:'get_clinic_info.php', data:"clinicNo=" + clinicNo, success:function(result){
				//jQuery("#clinicInDialog").attr("value", result.data.clinicNo);
				jQuery("#clinicName").attr("value", result.data.clinicName);
				jQuery("#clinicAddress").val(result.data.clinicAddress);
				jQuery("#detail").val(result.data.clinicDetail);
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
				alert(textStatus);
				alert(errorThrown);
			}
		});
		if( clinicObject.value == 0 ){
			jQuery("#AddClinicDialog").dialog("option", "buttons", [{text:"Add", id:"operateClinicButton", click:new Function("operateClinic()")}, {text:"Cancel", click:function(){jQuery(this).dialog("close");}}]);
		}else{
			jQuery("#AddClinicDialog").dialog("option", "buttons", [{text:"Update", id:"operateClinicButton", click:new Function("operateClinic()")}, {text:"Cancel", click:function(){jQuery(this).dialog("close");}}]);
			
		}
	}
	
	function uploadCallback(filename){
		if( filename == "" ){
			document.getElementById("portraitImg").src = "./picture";
		}else{
			document.getElementById("portraitImg").src = filename;
		}
		
		document.getElementById("portrait").outerHTML = document.getElementById("portrait").outerHTML;
		document.getElementById("portraitHidden").value = filename;
		document.getElementById("errorMsg").innerHTML = "";
		changeFunc();
		
	}



	function doctorPortraitSubmit(inputId, errorId, formId){
		var inputFile = document.getElementById(inputId);
		var errorObject = document.getElementById(errorId);
		var filePath = inputFile.value;
		var errorFlag = false;
		if( filePath == undefined || filePath=="" ){
			uploadCallback("");
			errorFlag = true;
		}else{
			var fileArr = filePath.split("//");
			var fileTArr = fileArr[fileArr.length - 1].toLowerCase().split(".");
			var fileType = fileTArr[fileTArr.length - 1].toLowerCase();
			if( fileType != "jpg" && fileType != "jpeg" && fileType != "bmp" && fileType != "png"){
				inputFile.focus();
				errorObject.innerHTML = "the file type error!!!";
				errorFlag = true;
			} 
		}

		if( errorFlag == false ){
			document.getElementById(formId).submit();
		}
	}

	function deleteObject(){
		var confirmResult = confirm("are you sure delete this doctor info???");
		if( confirmResult == false ){
			return;
		}

		
		var doctorNo = document.getElementById("doctorNo").value;
		jQuery.ajax({type:'post',async:false,data:"No=" + doctorNo + "&type=2", dataType:'json', url:'delete_op.php', success:function(result){
				if( result.data.status == "success" ){
					alert("delete doctor success!!!");
					isChange = false;
					previousPage();
					//document.getElementById("firstName").value = "";
					//document.getElementById("surname").value = "";
					//document.getElementById("title").value = "";

					//document.getElementById("knownAS").value = "";
					
					//jQuery("#address").val("");
					//document.getElementById("telephone").value = "";
					//document.getElementById("portraitImg").src = "";
					//document.getElementById("portraitHidden").value = "";
	
					//document.getElementById("submitButton").value = "Add";
					//document.getElementById("deleteButton").disabled = true;
					
				}else{
					document.getElementById("errorMsg").innerHTML = "delete doctor fail!!! " + result.data.msg;
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
			}
		});
		
	}


	function doctorSubmit(){
		var firstNameErrorObject = document.getElementById("firstNameError");
		var surnameErrorObject = document.getElementById("surnameError");
		var telephoneErrorObject = document.getElementById("telephoneError");
		firstNameErrorObject.innerHTML = "";
		surnameErrorObject.innerHTML = "";
		telephoneErrorObject.innerHTML = "";


		
		
		var firstNameErrorObject = document.getElementById("firstNameError");
		var surnameErrorObject = document.getElementById("surnameError");
		firstNameErrorObject.innerHTML = "";
		surnameErrorObject.innerHTML = "";
		var firstNameObject = document.getElementById("firstName");
		var surnameObject = document.getElementById("surname");

		var firstName = firstNameObject.value;
		var surname = surnameObject.value;
		if( firstName == "" ){
			firstNameErrorObject.innerHTML = "please input first name!!!";
			return false;
		}

		if( surname == "" ){
			surnameErrorObject.innerHTML = "please input surname!!!";
			return false;
		}

		var telephone = document.getElementById("telephone").value;
		if( telephone != "" ){
			var reg = new RegExp("^[0-9]+$");

			if( reg.test(telephone) == false ){
				telephoneErrorObject.innerHTML = "telephone format error!!!!";
				return false;
			}
		}
		var doctorNo = document.getElementById("doctorNo").value;
		var title = document.getElementById("title").value;
		var knownAS = document.getElementById("knownAS").value;
		var address = jQuery("#address").val();
		var portraitHidden = document.getElementById("portraitHidden").value;
		var isInCirculateList;
		if( document.getElementById("isInCirculateList").checked == true ){
			isInCirculateList = 1;
		}else{
			isInCirculateList = 0;
		}

		var clinicNo = document.getElementById("clinicNo").value;
		if( clinicNo == "" ){
			clinicNo = "null";
		}
		

		if( isChange == false ){
			alert("no change accur!!!");
			return;
		}
		var isSuccess = false;
		var postData = "doctorNo=" + doctorNo + "&doctorFirstName=" + firstName + "&doctorSurname=" + surname + "&doctorTitle=" + title + "&doctorKnownAs=" + knownAS + "&doctorAddress=" + address + "&doctorTelephone=" + telephone  + "&isInCirculateList=" +isInCirculateList + "&portraitHidden=" + portraitHidden + "&clinicNo=" + clinicNo;
		jQuery.ajax({type:'post', async:false, data:postData, url:"add_doctor.php",dataType:'json', success:function(result){
				if( result.data.status == "success" ){
					document.getElementById("doctorNo").value = result.data.doctorNo;
					//alert(result.data.msg);
					isChange = false;
					previousPage();
					document.getElementById("deleteButton").disabled = false;
					
					document.getElementById("submitButton").value = "Update";
					isSuccess = true;
					
				}else{
					alert(result.data.msg);
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
			}
		});
		return isSuccess;
	}


	function previousPage(){
		if( isChange == true ){
			jQuery("#leaveDialog").dialog("open");
			return;
		}
		
		window.location.href = "list_doctor.php";
		
	}

	function leaveBefore(){
		if( isChange == true ){
			return true;
		}
	}



</script>

</head>

<body onbeforeunload="return leaveBefore();">
	<div id="container">
		<div id="header"></div>
		<?php include_once 'nav.php';?>
		<?php 

			$doctorNo = 0;
			$doctorFirstName = "";
			$doctorSurname = "";
			$doctorTitle = "";
			$doctorKnownAs = "";
			$doctorAddress = "";
			$doctorTelephone = "";
			$inCirculateList = false;
			$portraitFile = "";
			$clinicNo = 0;
			
			$addOrUpdate;
			
			
			$ini_array = parse_ini_file("config/config.ini");
	
			$conn = @mysqli_connect($ini_array["host"], $ini_array["username"], $ini_array["password"], $ini_array["db_name"]) or die("cann't connect the mysql db");
			mysqli_set_charset($conn, "utf8");
			ini_set('default_charset', "UTF-8");
			
			if( isset($_GET["doctorNo"]) && strcmp(trim($_GET["doctorNo"]), "" ) != 0 && preg_match("/^[0-9]+$/", $_GET["doctorNo"]) == true ){
				$doctorNo = $_GET["doctorNo"];
				$doctorNo = mysqli_real_escape_string($conn, $doctorNo);
				$getDoctorInfo = "select doctor_first_name, doctor_surname, doctor_title, known_as, doctor_address, doctor_telephone_no,  inCirculateList, portrait_file,clinic_no  from doctor where Doctor_no=".$doctorNo;
				$doctorResult = mysqli_query($conn, $getDoctorInfo);
				if( $row = mysqli_fetch_array($doctorResult) ){
					$doctorFirstName = $row["doctor_first_name"];
					$doctorSurname = $row["doctor_surname"];
					$doctorTitle = $row["doctor_title"];
					$doctorKnownAs = $row["known_as"];
					$doctorAddress = $row["doctor_address"];
					$doctorTelephone = $row["doctor_telephone_no"];
					$inCirculateList = $row["inCirculateList"];
					$portraitFile = $row["portrait_file"];
					$clinicNo = $row["clinic_no"];
					$addOrUpdate = "Update";
				}else{
					$addOrUpdate = "Add";
				}
			}else{
				$getDoctorNoSql = "select max(doctor_no) max_no from doctor";
				$getDoctorResult = mysqli_query($conn, $getDoctorNoSql);
				$row = mysqli_fetch_array($getDoctorResult);
				$doctorNo = $row["max_no"] + 1;
				$addOrUpdate = "Add";
			}
			
			
			$getClinicSql = "select Clinic_no, Clinic_name from clinic";
			$clinicResult = mysqli_query($conn, $getClinicSql);
		?>
		<div id="main_content">
			<div id="doctorInfoDiv" style="margin:10px auto;width:1000px;">
				<table style="width:980px;">
					<tr>
						<td style="width:20%;text-align:right;height:60px;"><label>Doctor No.:</label></td>
						<td style="width:20%;"><input type="text" name="doctorNo" id="doctorNo" value="<?php echo $doctorNo?>" readonly="readonly"/></td>
						<td style="width:20%;"></td>
						<td style="width:20%;text-align:right;"><label>Address:</label></td>
						<td rowspan="2" style="width:20%;"><textarea name="address" id="address"  style="resize:none;height:5em;vertical-align:text-top;" onchange="changeFunc()"><?php echo $doctorAddress?></textarea></td>
					</tr>
					<tr>
						<td style="text-align:right;height:60px;"><label>First Name:</label></td>
						<td><input type="text" name="firstName" id="firstName" value="<?php echo $doctorFirstName?>" onchange="changeFunc()"/></td>
						<td><span id="firstNameError"></span></td>
						<td></td>
					</tr>
					<tr>
						<td  style="text-align:right;height:60px;"><label>Surname:</label></td>
						<td><input type="text" name="surname" id="surname" value="<?php echo $doctorSurname?>" onchange="changeFunc()"/></td>
						<td><span id="surnameError"></span></td>
						<td style="text-align:right;"><label>clinic:</label></td>
						<td>
							<select name="clinicNo" id="clinicNo" onchange="changeFunc()">
								<?php 
									while( $clinicRow = mysqli_fetch_array($clinicResult)){
								?>
								<option value="<?php echo $clinicRow["Clinic_no"]?>" <?php if( $clinicNo == $clinicRow["Clinic_no"] ) echo "selected=\"selected\";"?>><?php echo  $clinicRow["Clinic_name"]?></option>
								<?php }?>
							</select>
							
						</td>
					</tr>
					<tr>
						<td style="text-align:right;height:60px;"><label>Title:</label></td>
						<td><input type="text" name="title" id="title"value="<?php echo $doctorTitle?>" onchange="changeFunc()"/></td>
						<td></td>
						<td></td>
						<td><input type="button" value="Edit Clinic" onclick="popAddClinic()" /></td>
					</tr>
					<tr>
						<td style="text-align:right;height:60px;"><label>Known As:</label></td>
						<td><input type="text" name="knownAS" id="knownAS" value="<?php echo $doctorKnownAs?>" onchange="changeFunc()"/></td>
						<td  style="text-align:right;height:60px;"><label style="display:none;">Portrait:</label></td>
						<td rowspan="3"><img src="<?php echo $portraitFile?>" width="100px" height="100px" id="portraitImg" style="display:none;"/><input type="hidden" name="portraitHidden" value="<?php echo $portraitFile?>" id="portraitHidden" onchange="changeFunc()"/></td>
					</tr>
					<tr>
						<td style="text-align:right;height:60px;"><label>Telephone No.:</label></td>
						<td><input type="text" name="telephone" id="telephone" value="<?php echo $doctorTelephone?>" onchange="changeFunc()"/></td>
						<td><span id="telephoneError"></span></td>
						<td></td>
					</tr>
					<tr>
						<td style="text-align:right;height:60px;"><label>In Circulate List?:</label></td>
						<td><input type="checkbox" name="isInCirculateList" id="isInCirculateList" <?php if($inCirculateList == 1 ){echo "checked=\"checked\"";}?> onchange="changeFunc()"/></td>
						<td></td>
						<td></td>
					</tr>
					<tr>
						<td></td>
						<td></td>
						<td></td>
						<td colspan="2" rowspan="1">
							<form enctype="multipart/form-data" action="upload_op.php" method="post" target="hidden_frame" id="doctorPortraitForm" style="display:none;">
								<div id="fileUpload">
									<input type="file" name="portrait" id="portrait" />
									<input type="hidden" name="funcName" id="funcName" value="uploadCallback"/>
									<input type="button" value="upload" onclick="doctorPortraitSubmit('portrait', 'errorMsg', 'doctorPortraitForm')"/>
									<span id="errorMsg"></span>
								</div>
							</form>
						</td>
					</tr>
					
				</table>
			</div>
			
		
			<div id="operate" style="height:60px;">
				<input type="button" value="<?php echo $addOrUpdate?>" id="submitButton" onclick="doctorSubmit()"/>
				<input type="button" value="Delete" id="deleteButton" onclick="deleteObject()" <?php if(strcmp($addOrUpdate, "Add") == 0 ){echo "disabled=\"disabled\"";}?>/>
				<input type="button" value="Return" onclick="previousPage()"/><br />
				<div><label id="MSG"></label></div>
			</div>
			
		</div>
		
		<iframe id="hidden_frame" name="hidden_frame" style="display:none"></iframe>


			
		
		
		<div id="leaveDialog" title="leave dialog" style="display:none">
			<label>the doctor data have change, do  you save before leave?</label>
		</div>
		<?php include_once 'footer.php';?>
	</div>
	
	
	
		<?php 
			$clinicSql = "select Clinic_no, Clinic_name from clinic";
			$clinicResult = mysqli_query($conn, $clinicSql);
		?>
		<div id="AddClinicDialog" title="Operate CLinic" style="display:none"> 
			<div id="clinicDialogDiv"  >
				<table style="width:600px;">
					<tr>
						<td style="width:50%;text-align:right;"><label>Clinic List:</label> </td>
						<td style="width:50%;text-align:left;">
							<select name="clinicNoOpClinic" id="clinicNoOpClinic" onchange="getClinicInfo()">
								<option value="0">Add Clinic</option>
								<?php 
									while( $row = mysqli_fetch_array($clinicResult)){
										$clinicNoInClinic = $row["Clinic_no"];
										//if( $clinicNo == 0 ){
											//$clinicNo = $clinicNoInClinic;
										//}
										$clinicName = $row["Clinic_name"];
								?>
								<option  value="<?php echo $clinicNoInClinic?>"><?php echo $clinicName?></option>
								<?php }?>
							</select>
						</td>
					</tr>
					<tr>
						<td style="width:50%;text-align:right;"><label>Clinic Name:</label></td>
						<td style="width:50%;text-align:left;"><input type="text" name="clinicName" id="clinicName"/></td>
					</tr>
					<tr>
						<td style="width:50%;text-align:right;vertical-align:top;"><label>Clinic Address:</label></td>
						<td style="width:50%;text-align:left;" ><textarea name="clinicAddress" id="clinicAddress" style="resize:none;height:5em;"></textarea></td>
					</tr>
		
					<tr>
						<td style="width:50%;text-align:right;vertical-align:top;"><label>Clinic Detail:</label></td>
						<td style="width:50%;text-align:left;"><textarea name="detail" id="detail" style="resize:none;height:5em;"></textarea></td>
					</tr>
		
				</table>
			</div>
		</div>
</body>
</html>
